#!/user/bin/env python
# -*- coding:utf-8 -*-
#/home/zc/workspace/tinyfeet/trunk/src/controllers/upload.py

'''
上传文件
重命名文件（yyymmddhhmmss.png）
保存于/static/tfeet/images/目录
Created on 2011-10-20

@author: zc
'''
from __future__ import division
import web
from datetime import datetime
from config import settings
import Image
from controllers.utils import logger
logger = logger.logger()


def upload( x ):
    smallPic = None
    norPic = None
    orgPic = None
    
    if 'myfile' in x: # to check if the file-object is created
        t = datetime.now()
        cdate = t.strftime( "%Y%m%d%H%M%S" ) + str( t.microsecond )

        filepath = x.myfile.filename.replace( '\\', '/' )   # replaces the windows-style slashes with linux ones.
        filename = cdate + "." + filepath.split( '/' )[-1].split( '.' )[-1]                # splits the and chooses the last part (the filename with extension)
        fout = open( settings.UPLOAD_DIRS + filename, 'w' )        # creates the file where the uploaded file should be stored
        fout.write( x.myfile.file.read() )               # writes the uploaded file to the newly created file.
        fout.close()                                   # closes the file, upload complete.
        print 'upload done'
        orgPic = settings.UPLOAD_DIRS + filename 
        #compress image to small and normal size
        isDone, smallPic, norPic = resizePic( orgPic )
        if isDone <> 0:
            smallPic, norPic, orgPic = None

    return smallPic, norPic , orgPic


def resizePic( picPath ):
    """ 处理图片到small和normal
    图片原始大小宽超过800"""
    
    smallPath = picPath[:picPath.index( '.' )] + "_s." + picPath.split( '/' )[-1].split( '.' )[-1] #缩略图
    norPath = picPath[:picPath.index( '.' )] + "_n." + picPath.split( '/' )[-1].split( '.' )[-1] #合适的尺寸
    res = -1 
    
    im = Image.open( picPath )
    originalWidth, originalHeight = im.getbbox()[2:]

    ruleWidth = settings.RULEWIDTH
    smallRate = settings.PICRATE 

    try:
        if originalWidth > ruleWidth:
            norWidth = int( originalWidth * ( ruleWidth / originalWidth ) )
            norHeight = int( norWidth * ( originalHeight / originalWidth ) )
            norPic = im.resize( ( norWidth, norHeight ) )
            norPic.save( norPath )            
        else:
            norWidth = originalWidth 
            norHeight = originalHeight
            im.save( norPath )    
            
        smallWidth = int( smallRate * norWidth )
        smallHeight = int( smallRate * norHeight )
        samllPic = im.resize( ( smallWidth, smallHeight ) )
        samllPic.save( smallPath )
    except Exception, data:
        res = -1
        logger.error( "upload image faild:%s" % data )
        print "upload image faild:", data
    else:
        res = 0
        
    return res, smallPath, norPath
    #raise web.seeother('/upload')
